import os
import dicom

def getDICOMProperty(ddir='./',prop='EchoTime'):
    try:
        files = os.listdir(ddir)
        for file in files:
            fn = os.path.join(ddir,file)
            dfile = dicom.dicom(filename=fn)
            try:
                hdr = dfile.dicomTags()
                
                try:
                    dprop = hdr[prop]
                    return dprop
                except:
                    pass
            except:
                pass
    except Exception, error:
        print "couldn't match property", error
        
def orderDirectoriesByProperty(ddirs = [], prop = 'EchoTime', num=''):
    try:
        matched = {}
        for ddir in ddirs:
            print ddir
            dprop = getDICOMProperty(ddir,prop)
            if( dprop ):
                if( num ):
                    dprop = eval('%s(%s)'%(num,dprop))
                matched[dprop] = ddir

        keys = matched.keys()

        keys.sort()
        data = []
        for key in keys:
            data.append(matched[key])
            
        return keys, data
    except Exeption, error:
        print "failed in orderDirectoriesByProperty", error
        
